import { MdlDialogService, MdlSnackbarService } from '@angular-mdl/core';
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';

import { ManageService } from '../../services/manage-service';
import { SessionService } from '../../services/session-service';
import { Admin, Manage, SearchRet } from '../../shared/model/defination';

@Component({
    selector: 'app-manage',
    templateUrl: './manage.component.html',
    styleUrls: ['./manage.component.scss'],
    providers: [ManageService]
})
export class ManageComponent implements OnInit {
    columns: any[] = [];
    public roleTypeNameMap: any = {
        AppServicesProjectProject: '项目管理员',
        AppServicesCompanyCompany: '公司行政／HR'
    };
    public cachedRows: any[] = [];
    public selected: Array<Manage> = [];
    public searchRequest: any = {};
    public count: number = 0;
    public offset: number = 0;
    public limit: number = 10;
    public deleteId: number = 0;
    public isPageLoading: boolean = false;
    public rows = [];
    public pagerMessage = {
        emptyMessage: '没有数据',
        totalMessage: '总计'
    };

    constructor(
        private _manageSerivce: ManageService,
        private _sessionService: SessionService,
        private _router: Router,
        private _snackService: MdlSnackbarService,
        private _dialogService: MdlDialogService
    ) {}

    get Selected() {
        return this.selected.map(a => {
            return {
                id: a.id,
                userName: a.userName,
                email: a.email,
                mobile: a.mobile,
                companyId: a.companyId,
                status: a.status,
                roleIds: a.roles.map(r => r.id)
            };
        });
    }

    async ngOnInit() {
        const session: Admin = await this._sessionService.getCurrentUser();
        // this.userRole = session.roles[0];

        this.page(this.offset, this.limit);
    }
    // private _getControledRoles() {
    //   let indexOrder = USER_ROLE.indexOf(this.userRole.roleName.toLowerCase());
    //   return USER_ROLE.filter(r => USER_ROLE.indexOf(r) > indexOrder);
    // }
    _constructQuery() {
        const criteria: any = {};
        if (this._sessionService.isUserProperty) {
            criteria.projectId = this._sessionService.Managable.id;
        }
        return criteria;
    }
    async page(offset, limit) {
        this.isPageLoading = true;
        const criteria: any = this._constructQuery();
        criteria.pageNumber = offset + 1;
        criteria.pageSize = this.limit;
        // if (this.searchRequest.userName) {
        //     criteria.userName = this.searchRequest.userName;
        // }
        // if (this.searchRequest.telephone) {
        //     criteria.phone = this.searchRequest.mobile;
        // }
        try {
            const action$ = <Observable<
                SearchRet<Manage>
            >>this._manageSerivce.Search(criteria);
            const searchRet: any = await action$.toPromise();
            // searchRet.items.forEach(item => {
            //   let mngr = item.managements;
            //   if (mngr.length) {
            //     item.type = mngr.manage_type === "App\Services\Project\Project" ? '公司管理员' : '人事管理员';
            //   }
            // });
            this.count = searchRet.totalPageRecords;

            const start = offset * limit;
            const end = start + limit;
            const rows = [...this.rows];

            for (let i = start; i < end; i++) {
                rows[i] = searchRet.items[i - start];
            }
            this.cachedRows = rows;
            // this.rows = rows;
            this.rows = searchRet.items;
            this.isPageLoading = false;
            console.log('Page Results', start, end, rows);
        } catch (e) {
            if (e.status === 401) {
                this._router.navigate(['/login']);
            }
        } finally {
        }
    }

    async unlockAccount() {
        try {
            this.selected.forEach(s => (s.status = 1));
            await this._manageSerivce.batchUpdate(this.Selected);
            this._snackService.showToast('更新成功');
            this.selected = [];
        } catch (e) {
            console.error(e);
        } finally {
        }
    }
    async lockAccount() {
        try {
            this.selected.forEach(s => (s.status = 0));
            await this._manageSerivce.batchUpdate(this.Selected);
            this._snackService.showToast('更新成功');
            this.selected = [];
        } catch (e) {
            console.error(e);
        } finally {
        }
    }

    async delete(id) {
        try {
            await this._dialogService
                .confirm('确定删除此管理员？', '取消', '确认')
                .toPromise();
            await this._manageSerivce.Delete(+id).toPromise();
            await this.ngOnInit();
        } catch (e) {
            console.log(e);
        } finally {
        }
    }

    onPage(event) {
        console.log('Page Event', event);
        this.page(event.offset, event.limit);
    }
}
